﻿using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.ApproveManager;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.ApproveExt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Approve
{
    public class Approve_MainHandle
    {
        private readonly SJDBContext _context;

        public Approve_MainHandle(SJDBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> CreateAsync(ApproveMain entity)
        {
            try
            {
                _context.ApproveMains.Add(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>Create", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(ApproveMain entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新特定内容
        /// </summary>
        /// <param name="entityExt"></param>
        /// <returns></returns>
        public async Task<bool> UpdateApproveMainSpecificContentAsync(ApproveMainUpdateModelExtend entityExt)
        {
            try
            {
                ApproveMain entity = entityExt.ExtMapToEntity<ApproveMain, ApproveMainUpdateModelExtend>();
                _context.Attach(entity);
                foreach (var property in entityExt.UpdateProperties)
                {
                    _context.Entry(entity).Property(property).IsModified = true;
                }
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>UpdateApproveMainSpecificContentAsync", ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(ApproveMain entity)
        {
            try
            {
                _context.ApproveMains.Remove(entity);
                return _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>Delete", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            try
            {
                var entity = _context.ApproveMains.Find(id);
                if (entity != null)
                {
                    _context.ApproveMains.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>DeleteById", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据外部ID删除
        /// </summary>
        /// <param name="fId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByFIdAsync(string fId)
        {
            try
            {
                var approves = await _context.ApproveMains.Where(a => a.FId == fId).ToListAsync();
                int count = _context.Database.ExecuteSqlRaw($"delete from approve_main where Fid='{fId}';");
                return approves.Count == count;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>DeleteByFIdAsync", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApproveMain> GetEntityByIdAsync(string id)
        {
            try
            {
                return await _context.ApproveMains.FindAsync(id);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>GetEntityById", ex);
            }
            return null;
        }

        /// <summary>
        /// 根据外部ID获取实体
        /// </summary>
        /// <param name="fId"></param>
        /// <returns></returns>
        public async Task<ApproveMain> GetEntityByFIdAsync(string fId)
        {
            try
            {
                return await _context.ApproveMains.Where(m => m.FId == fId).FirstAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>GetEntityByFIdAsync", ex);
            }
            return null;
        }


        /// <summary>
        /// 分页获取所有审批流
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<(List<ApproveMain> approves, int count)> GetAllAsync(int pageNumber, int pageSize, Expression<Func<ApproveMain, bool>> condition = null)
        {
            try
            {
                var query = _context.ApproveMains.AsQueryable();

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }

                //总条数
                int count = await query.CountAsync();

                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                query = query.OrderBy(order => order.SubmitTime).Skip(skip).Take(pageSize);

                // 执行查询并返回结果
                var approves = await query.ToListAsync();
                return (approves, count);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Approve_MainHandle=>GetAllAsync  page", ex);
            }
            return (null, 0);
        }

        /// <summary>
        /// 分页获取所有待办审批流
        /// </summary>
        /// <param name="pageNumber">当前页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="condition">筛选条件</param>
        /// <returns>包含审批流列表及总条数的元组</returns>
        public async Task<(List<ApproveMain> approves, int count)> GetWaitToBeDoneApproveMainAsync(int pageNumber, int pageSize, Expression<Func<ApproveRecord, bool>> conditionR = null, Expression<Func<ApproveMain, bool>> conditionM = null)
        {
            try
            {
                var query = _context.ApproveRecords.AsQueryable();
                if (conditionR != null)
                {
                    query = query.Where(conditionR);
                }

                // 选择主表数据
                var mainQuery = from r in query
                                join main in _context.ApproveMains on r.PId equals main.Id
                                select main;
                // 如果提供了查询条件，则应用它
                if (conditionM != null)
                {
                    mainQuery = mainQuery.Where(conditionM);
                }

                // 总条数
                int count = await mainQuery.CountAsync();

                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                var pagedQuery = mainQuery.OrderBy(order => order.SubmitTime).Skip(skip).Take(pageSize);

                // 执行查询并返回结果
                var approves = await pagedQuery.ToListAsync();

                return (approves, count);
            }
            catch (Exception ex)
            {
                // 记录错误日志
                LogManager.WriteError("Approve_MainHandle=>GetWaitToBeDoneApproveMainAsync", ex);
                // 可能需要重新抛出异常或处理异常
                throw;
            }
        }

    }
}
